<template>
  <div
    v-if="visible"
    class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm transition-opacity duration-300"
    :class="{ 'opacity-0 pointer-events-none': !visible }"
  >
    <div
      class="relative w-full max-w-4xl max-h-[90vh] bg-white dark:bg-gray-800 rounded-xl shadow-xl overflow-hidden transform transition-all duration-300 scale-95 opacity-0"
      :class="{ 'scale-100 opacity-100': visible }"
    >
      <!-- 弹窗头部 -->
      <div
        class="bg-gray-50 dark:bg-gray-700 px-6 py-4 border-b border-gray-200 dark:border-gray-600 flex justify-between items-center"
      >
        <h3 class="text-lg font-semibold text-gray-800 dark:text-white">
          Ai代码分析
        </h3>
        <button
          @click="handleClose"
          class="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 transition-colors"
        >
          <i class="fa-solid fa-times"></i>
        </button>
      </div>

      <!-- 内容区域 -->
      <div
        class="p-6 overflow-y-auto max-h-[calc(90vh-120px)] markdown-body"
        v-html="parsedMarkdown"
      ></div>

      <!-- 底部操作区 -->
      <div
        class="bg-gray-50 dark:bg-gray-700 px-6 py-3 border-t border-gray-200 dark:border-gray-600 flex justify-end"
      >
        <button
          @click="handleClose"
          class="px-4 py-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-600 dark:hover:bg-gray-500 text-gray-800 dark:text-white rounded-lg transition-colors"
        >
          关闭
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from "vue";
import { defineProps, defineEmits } from "vue";
// 接收props
const props = defineProps({
  markdown: {
    type: String,
    required: true,
  },
  visible: {
    type: Boolean,
    default: false,
  },
});

// 定义emits
const emits = defineEmits(["update:visible"]);

// 解析后的HTML
const parsedMarkdown = ref("");

// 关闭弹窗
const handleClose = () => {
  // 添加关闭动画
  emits("update:visible", false);
};

// 初始化marked.js
const initMarkedJS = () => {
  return new Promise((resolve, reject) => {
    if (window.marked) {
      resolve(window.marked);
      return;
    }

    const script = document.createElement("script");
    script.src = "https://cdn.jsdelivr.net/npm/marked/marked.min.js";
    script.onload = () => resolve(window.marked);
    script.onerror = reject;
    document.body.appendChild(script);
  });
};

// 初始化highlight.js
const initHighlightJS = () => {
  return new Promise((resolve, reject) => {
    if (window.hljs) {
      resolve(window.hljs);
      return;
    }

    const script = document.createElement("script");
    script.src =
      "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js";
    script.onload = () => {
      const style = document.createElement("link");
      style.href =
        "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github-dark.min.css";
      style.rel = "stylesheet";
      document.head.appendChild(style);
      resolve(window.hljs);
    };
    script.onerror = reject;
    document.body.appendChild(script);
  });
};

// 解析Markdown
const parseMarkdown = async () => {
  try {
    const marked = await initMarkedJS();
    parsedMarkdown.value = marked.parse(props.markdown || "");

    // 等待DOM更新后高亮代码
    nextTick(() => {
      highlightCodeBlocks();
    });
  } catch (error) {
    console.error("Failed to parse Markdown:", error);
    parsedMarkdown.value = `<div class="text-red-500">解析Markdown失败: ${error.message}</div>`;
  }
};

// 高亮代码块
const highlightCodeBlocks = async () => {
  try {
    const hljs = await initHighlightJS();
    const codeBlocks = document.querySelectorAll(".markdown-body pre code");
    codeBlocks.forEach((block) => {
      hljs.highlightElement(block);
    });
  } catch (error) {
    console.error("Failed to initialize syntax highlighting:", error);
  }
};

// 监听markdown变化
watch(() => props.markdown, parseMarkdown);

// 监听visible变化
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      // 弹窗显示后解析Markdown
      parseMarkdown();
    }
  }
);

// 初始化
onMounted(() => {
  if (props.visible) {
    parseMarkdown();
  }
});
</script>

<style scoped>
.markdown-body h1 {
  @apply text-2xl font-bold text-gray-800 dark:text-gray-100 mb-4;
}

.markdown-body h2 {
  @apply text-xl font-bold text-gray-800 dark:text-gray-100 mb-3;
}

.markdown-body h3 {
  @apply text-lg font-bold text-gray-800 dark:text-gray-100 mb-2;
}

.markdown-body p {
  @apply text-gray-700 dark:text-gray-300 mb-4 leading-relaxed;
}

.markdown-body a {
  @apply text-primary hover:underline;
}

.markdown-body ul,
.markdown-body ol {
  @apply mb-4 ml-6;
}

.markdown-body ul {
  @apply list-disc;
}

.markdown-body ol {
  @apply list-decimal;
}

.markdown-body li {
  @apply text-gray-700 dark:text-gray-300 mb-2;
}

.markdown-body blockquote {
  @apply border-l-4 border-primary pl-4 italic text-gray-600 dark:text-gray-400 my-4;
}

.markdown-body code:not(pre code) {
  @apply bg-gray-100 dark:bg-gray-800 px-1 py-0.5 rounded text-sm font-mono;
}

.markdown-body pre {
  @apply bg-gray-100 dark:bg-gray-800 rounded p-4 my-4 overflow-x-auto;
}

.markdown-body img {
  @apply max-w-full rounded-lg my-4;
}
</style>
